package frame;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import common.User;
import function.AgreeFriendApply;
import function.GetMessage;
import function.SendMessage;
import global.Const;
import global.PublciVariable;
import other.DButton;
import other.HeadImage;
import panel.common.BackGround;
import panel.common.MessagePanel;
import panel.home.ChatMessage;
import thread.Sleep;
import windows.MessageDialog;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;


public class Chat extends JFrame implements Runnable {
    private User user;
    private boolean isAlive = true;
    public static MessageDialog messageDialog = new MessageDialog();
    MessagePanel messagePanel = new MessagePanel();
    public JTextArea textArea = new JTextArea();
    Thread thread;

    public Chat(User user) {
        this.user = user;
        init();
    }

    private void init() {
        // 添加聊天到列表
        PublciVariable.chatList.put(user.username, true);

        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setSize(Const.FRAME_WIDTH, Const.FRAME_HEIGHT);
        setLocationRelativeTo(null);
        setResizable(false);
        setBackground(null);
        setTitle(user.username);
        setLayout(null);

        // 状态栏
        JPanel statusBar = getStatusBar(user);

        // 消息界面
        messagePanel.setBounds(0, 80, Const.PANEL_WIDTH, 816);

        // 编辑栏
        JPanel editBar = getEditBar(user);

        // 添加组件
        add(messageDialog);
        add(statusBar);
        add(messagePanel);
        add(editBar);
        add(new BackGround("src/main/resources/image/home/firefly.jpg"));

        // 关闭前操作
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                close();
            }
        });

        // 启动
        setVisible(true);
        listen();
    }

    private static JPanel getStatusBar(User user) {
        JPanel statusBar = new JPanel();
        statusBar.setLayout(null);
        statusBar.setBackground(new Color(255, 255, 255, 150));
        statusBar.setBounds(0, 0, Const.PANEL_WIDTH, 80);
        // 头像
        HeadImage headImage = new HeadImage(user.username);
        headImage.setSize(80);
        // 用户名
        JLabel usernameLabel = new JLabel(user.username);
        usernameLabel.setFont(new Font("宋体", Font.PLAIN, 80));
        usernameLabel.setHorizontalAlignment(SwingConstants.CENTER);
        usernameLabel.setHorizontalAlignment(SwingConstants.CENTER);
        usernameLabel.setForeground(Color.black);
        usernameLabel.setBounds(0, 0, 540, 80);
        // 添加组件
        statusBar.add(headImage);
        statusBar.add(usernameLabel);
        return statusBar;
    }

    private JPanel getEditBar(User user) {
        JPanel editBar = new JPanel();
        editBar.setLayout(null);
        editBar.setBackground(Color.white);
        editBar.setBounds(0, 896, Const.PANEL_WIDTH, 64);
        // 图片按钮 (有bug，待开发)
//        DButton imageButton = new DButton(new ImageIcon("src/main/resources/icon/home/image.png"));
//        imageButton.setLocation(0, 0);
//        imageButton.addActionListener(e -> sendImage(user));
        // 文本框
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(64, 0, 412, 64);
        textArea.setBounds(0, 0, 412, 64);
        textArea.setLineWrap(true); // 设置自动换行
        textArea.setWrapStyleWord(true); // 设置单词边界换行
        textArea.setFont(new Font("宋体", Font.PLAIN, 25)); // 设置字体
        // 监听回车
        textArea.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
//                    sendMessage();
                }
            }
        });
        scrollPane.setViewportView(textArea);

        // 发送按钮
        DButton sendButton = new DButton(new ImageIcon("src/main/resources/icon/home/send.png"));
        sendButton.setLocation(476, 0);
        sendButton.addActionListener(e -> sendMessage());
        // 添加组件
//        editBar.add(imageButton);
        editBar.add(scrollPane);
        editBar.add(sendButton);
        return editBar;
    }

    private void sendMessage() {
        if (textArea.getText().isEmpty()) return;
        if (textArea.getText().length() > 1000) {
            messageDialog.open("消息长度不能超过1000");
            return;
        }
        SendMessage.send(user.username, textArea.getText(), PublciVariable.username);
        messagePanel.addMessage(new ChatMessage(textArea.getText()), true);
//            messagePanel.addMessage(new ChatMessage(new ImageIcon("src/main/resources/image/home/searchUser.jpg")), false);
        textArea.setText(null);
    }

    public static void sendImage(User user) {
        JFileChooser fileChooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("图片文件", "jpg", "jpeg", "png", "gif");
        fileChooser.setFileFilter(filter);
        int returnValue = fileChooser.showOpenDialog(null);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            String path = fileChooser.getSelectedFile().getAbsolutePath();
            // 判断文件后缀名
            if (!path.endsWith(".jpg") && !path.endsWith(".png") && !path.endsWith(".gif")) {
                messageDialog.open("只能发送图片文件");
                return;
            }
            System.out.print("发送图片：" + path + "\n");
            SendMessage.send(user.username, new ImageIcon(path), PublciVariable.username);
        }
    }

    public void listen() {
        thread = new Thread(this);
        thread.start();
    }

    public void close() {
        isAlive = false;
        PublciVariable.chatList.put(user.username, null);
        dispose();
    }

    public void input(JSONArray data) {
        for (Object i : data) {
            JSONObject message = (JSONObject) i;
            // 文本类
            if (message.getString("type").equals("text"))
                messagePanel.addMessage(new ChatMessage(message.getString("text")), false);
                // 图片类
            else if (message.getString("type").equals("image"))
                messagePanel.addMessage(new ChatMessage(new ImageIcon(message.getString("byte[]"))), false);
            else if (message.getString("type").equals("apply"))
                AgreeFriendApply.send(PublciVariable.username, message.getString("sender"));
        }
    }

    // 监听消息
    @Override
    public void run() {
        while (isAlive) {
            JSONArray local = PublciVariable.messageList.getJSONArray(user.username);
            if (local != null)
                System.out.print("显示消息" + PublciVariable.messageList.toString(JSONWriter.Feature.PrettyFormat) + "\n");
            PublciVariable.messageList.put(user.username, null);
            // 有消息
            if (local != null && !local.isEmpty())
                    input(local);
            Sleep.sleep(100);
        }
    }
}
